package com.handinglian.ai.common.util;

import cn.hutool.core.util.StrUtil;
import com.handinglian.ai.common.dto.ResultCode;
import com.handinglian.ai.common.exception.BizException;
import com.handinglian.ai.thirdparty.constants.MessageConstants;
import com.handinglian.ai.thirdparty.enums.TemplateTypeEnum;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class GeneralUtil {

    /**
     * 将传参List与数据库List进行比较，获取数据库需要删除的部分
     *
     * @param parameterList 传参List
     * @param databaseList   数据库List
     * @return java.util.List<T>
     * @author pxl
     * @date 2019/6/5 14:55
     */
    public static <T> List<T> getMissingList(List<T> parameterList, List<T> databaseList) {
        List missingList = new ArrayList();
        for (T databaseId : databaseList) {
            if (!parameterList.contains(databaseId)) {
                missingList.add(databaseId);
            }
        }
        return missingList;
    }

    /**
     * 将传参List与数据库List进行比较，获取数据库需要增加的部分
     *
     * @param parameterList 传参List
     * @param databaseList   数据库List
     * @return java.util.List<T>
     * @author pxl
     * @date 2019/6/5 14:55
     */
    public static <T> List<T> getAddList(List<T> parameterList, List<T> databaseList) {
        List addList = new ArrayList();
        for (T parameterId : parameterList) {
            if (!databaseList.contains(parameterId)) {
                addList.add(parameterId);
            }
        }
        return addList;
    }

    /**
    * 对未加 : 的macIp每两位加一个 :
    * @author pxl
    * @param macIp
    * @return java.lang.String
    * @date 2019/6/5 15:20
    */
    public static String processMacIp(String macIp) {
        if (macIp.indexOf(":") == -1){
            boolean flag = macIp.length() % 2 == 1 ? true : false;
            if (flag){
                throw new BizException(ResultCode.FAILED.getCode(), "macIp格式不正确，长度应为双数!");
            }
            StringBuffer stringBuffer = new StringBuffer(macIp);
            Integer index = 2;
            for (int i = 1; i < macIp.length()/2;i++) {
                stringBuffer.insert(index, ":");
                index = index + 3;
            }
            return stringBuffer.toString();
        } else {
            return macIp;
        }

    }

    /**
     * 判断是否是手机号
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
    * 生成uuid
    * @author pxl
    * @param
    * @return java.lang.String
    * @date 2019/8/21 11:37
    */
    public static String randomUUID() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        return uuid;
    }

    /**
     * 打包下载文件
     * @author pxl
     * @param fileList 文件列表
     * @param zipFileName 打包文件名
     * @return java.lang.String
     * @date 2019/8/22 14:55
     */
    public static String downZipManyFile(List<File> fileList, String zipFileName) throws IOException {
        BufferedInputStream br = null;//输入流
        ZipOutputStream out = null; // 压缩文件输出流
        int size;

        // 定义缓冲区
        byte[] buffer = new  byte[2048];
        if(fileList.size()>0){
            out = new ZipOutputStream(new FileOutputStream(zipFileName));
            for (int i = 0; i < fileList.size(); i++) {
                File f =fileList.get(i);
                out.putNextEntry(new ZipEntry(f.getName()));
                br = new BufferedInputStream(new FileInputStream(f));
                while((size=br.read(buffer))!=-1){
                    out.write(buffer,0,size);
                    out.flush();
                }
            }
            if(br!=null){br.close();}
            if(out!=null){out.close();}
        }
        return zipFileName;
    }

    /**
     * 获得用户远程地址
     */
    public static String getRemoteAddr(HttpServletRequest request){
        String remoteAddr = request.getHeader("X-Real-IP");
        if (StrUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        }else if (StrUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        }else if (StrUtil.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }

    /**
     * 如果对象为空，则使用defaultVal值
     * 	see: ObjectUtils.toString(obj, defaultVal)
     * @param obj
     * @param defaultVal
     * @return
     */
    public static String toString(final Object obj, final String defaultVal) {
        return obj == null ? defaultVal : obj.toString();
    }

    /**
     * 将字符串按照分隔符转换成相应类型的List
     * @author pxl
     * @param str 字符串
     * @param punctuations 分隔符
     * @return java.util.List<java.lang.Long>
     * @date 2019/6/5 15:44
     */
    public static List<Integer> stringToIntegerList(String str, String... punctuations){
        String punctuation = punctuations.length > 0?punctuations[0]:",";
        List<Integer> list = new ArrayList<>();
        String[] strArray = StrUtil.isBlank(str)?new String[0]:str.split(punctuation);
        for (String string : strArray){
            list.add(Integer.valueOf(string));
        }
        return list;
    }
}
